package cn.flyboy.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.flyboy.entity.*;
import cn.flyboy.service.ExamService;
import cn.flyboy.service.StudentService;
import cn.flyboy.service.TeacherService;
import cn.flyboy.utils.ExcleUtils;
import cn.flyboy.utils.FileHelper;
import cn.flyboy.utils.PagingSize;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class ExamController {
    @Resource
    private ExamService examServiceImpl;

    @Resource
    private TeacherService teacherServiceImpl;

    @Resource
    private StudentService studentServiceImpl;

    @RequestMapping("examStart")
    public String examStart(HttpSession session) {
        int index = examServiceImpl.selStartExam().size();
        System.out.println(index);
        if (index >= 1) {
            session.setAttribute("info", "<script>alert('当前存在已开启的考试');</script>");
        } else {
            int index1 = examServiceImpl.examStart(((Exam) session.getAttribute("exam")).getE_name());
            if (index1 >= 1) {
                session.setAttribute("info", "<script>alert('考试开启成功');</script>");
            } else {
                session.setAttribute("info", "<script>alert('考试开启失败');</script>");
            }
        }
        return "redirect:/teacher/teacher_exam_before.jsp";
    }

    // 保存学生上传答案
    @RequestMapping("saveAnswer")
    public String saveAnswer(MultipartFile paper, String stu_id, String stu_exam, HttpServletRequest req, HttpSession session) {
        System.out.println(stu_id + "***********************************************" + stu_exam);
        boolean index = examServiceImpl.saveAnswer(paper, req, session, stu_id, stu_exam);
        if (index) {
            session.setAttribute("info", "<script>alert('文件上传成功');</script>");
        } else {
            session.setAttribute("info", "<script>alert('文件上传失败');</script>");
        }
        return "redirect:/student/student_home.jsp";
    }

    // 下载试卷
    @RequestMapping("examDownload")
    public void examDownload(String e_name, String e_teacher, HttpServletResponse res, HttpServletRequest req) throws IOException {
        String fileName = examServiceImpl.selFileByName(e_name, e_teacher);
        System.out.println(fileName);
        res.reset();  // 清空缓存
        res.setCharacterEncoding("UTF-8");  // 字符编码
        res.setContentType("multipart/form-data"); // 二进制传输数据
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream os = res.getOutputStream();

        File file = new File(req.getServletContext().getRealPath("/upload/" + e_name), fileName);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }

    // 保存试卷
    @RequestMapping("savePaper")
    public String savePaper(@RequestParam("paper") MultipartFile paper, HttpServletRequest req, HttpSession session) throws IOException {
        boolean index = examServiceImpl.savePager(paper, req, session);
        if (index) {
            session.setAttribute("info", "<script>alert('文件上传成功');</script>");
        } else {
            session.setAttribute("info", "<script>alert('文件上传失败');</script>");
        }
        return "redirect:/teacher/teacher_addexam.jsp";
    }

    @RequestMapping(value = "getStartExamInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg getStartExamInfo(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, HttpSession session, HttpServletRequest request) {
        List<Exam> exams = examServiceImpl.selStartExam();
        if (exams.size() > 1) {
            Msg.fail().setMsg("当前存在多场考试，请联系管理员");
        } else if (exams.size() == 1) {
            int spiltPageCount = PagingSize.splitPageSize(request);
            // 查询之前调用startPage，传入分码，以及分页大小
            PageHelper.startPage(pageNum, spiltPageCount);
            // startPage紧跟的查询就是分页查询
            List<Student> lists = studentServiceImpl.selAllStudents(exams.get(0).getE_name(), exams.get(0).getE_teacher());

            // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
            // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
            PageInfo<Student> page = new PageInfo<Student>(lists, StaticResources.navigatePages);
            session.setAttribute("pageInfo", page);
            System.out.println("总页码：" + page.getPages());
            System.out.println("总记录数：" + page.getTotal());
            return Msg.success().add("pageInfo", page);
        } else {
            Msg.fail().setMsg("当前不存在考试");
        }
        return Msg.fail().setMsg("发生未知错误");
    }

    @RequestMapping(value = "getStartExamInfos", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg getStartExamInfos(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, HttpSession session) {
        List<Exam> exams = examServiceImpl.selStartExam();
        if (exams.size() > 1) {
            Msg.fail().setMsg("当前存在多场考试，请联系管理员");
        } else if (exams.size() == 1) {
            List<Student> lists = studentServiceImpl.selAllStudents(exams.get(0).getE_name(), exams.get(0).getE_teacher());
            return Msg.success().add("lists", lists);
        } else {
            Msg.fail().setMsg("当前不存在考试");
        }
        return Msg.fail().setMsg("发生未知错误");
    }

    @RequestMapping("getStartExam")
    @ResponseBody
    public int getStartExam(HttpSession session) {
        return examServiceImpl.selStartExam().size();
    }

    @RequestMapping("getStartExam_Student")
    @ResponseBody
    public String getStartExam_Stu(HttpSession session) {
        List<Exam> list = examServiceImpl.selStartExam();

        System.out.println("+++++++++++" + list);

        if (list == null || list.size() == 0)
            return "200";
        else {
            session.setAttribute("startExamName", list.get(0).getE_name());
            return list.get(0).getE_name();
        }
    }


    @RequestMapping("stopExam")
    @ResponseBody
    public void stopExam(String name, HttpSession session) {
        int index = examServiceImpl.updStopExam(name);
        if (index >= 1) {
            session.removeAttribute("examStartName");
            System.out.println("考试停止成功");
        } else {
            System.out.println("考试停止失败");
        }
    }

    @RequestMapping(value = "clearExam", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void clearExam(String name, String teaName, HttpSession session, HttpServletRequest req) {

        System.out.println(name + "******************" + teaName);

        int index0 = examServiceImpl.updClearExam(name);
        int index1 = teacherServiceImpl.delAnswer(name, teaName);
        int index2 = teacherServiceImpl.delStudentOfExam(name);
        int index3 = teacherServiceImpl.delExam(name, teaName);

        String folderPath = req.getServletContext().getRealPath("/files/" + name);
        String examPath = req.getServletContext().getRealPath("/upload/" + name);
        String stuExamPath = req.getServletContext().getRealPath("/WEB-INF/files/" + name);

        if (index0 >= 1 && index1 >= 1 && index2 >= 1 && index3 >= 0) {
            FileHelper.deleteFile(folderPath);
            FileHelper.deleteFile(examPath);
            FileHelper.deleteFile(stuExamPath);
            System.out.println("考试清理成功");
        } else {
            System.out.println("考试清理失败");
        }
    }

    @RequestMapping(value = "clearExamAdmin", method = {RequestMethod.GET, RequestMethod.POST})
    public String clearExam1(String name, String teaName, HttpServletRequest req) {

        int index0 = examServiceImpl.updClearExam(name);
        int index1 = teacherServiceImpl.delAnswer(name, teaName);
        int index2 = teacherServiceImpl.delStudentOfExam(name);
        int index3 = teacherServiceImpl.delExam(name, teaName);

        String folderPath = req.getServletContext().getRealPath("/files/" + name);

        if (index0 >= 1 && index1 >= 1 && index2 >= 1 && index3 >= 0) {
            FileHelper.deleteFile(folderPath);
            System.out.println("考试清理成功");
            return "redirect:/admin/admin_clearExam.jsp";
        } else {
            System.out.println("考试清理失败");
            return "redirect:/errors/error.jsp";
        }
    }

    @RequestMapping(value = "detailExam", method = {RequestMethod.GET, RequestMethod.POST})
    public String detailExam(String name, String teaName, HttpSession session) {
        List<Answer> lists = teacherServiceImpl.selFileAnswerName(name, teaName);
        session.setAttribute("answerList", lists);
        session.setAttribute("name", name);
        session.setAttribute("teaName", teaName);
        return "redirect:/teacher/teacher_after_detail.jsp";
    }


    @RequestMapping(value = "exportExam", method = {RequestMethod.GET, RequestMethod.POST})
    public String exportExam(String name, String teaName, HttpServletResponse response) {

        System.out.println("++++++++++++" + name + "*****************" + teaName);

        List<the_answer> lists = teacherServiceImpl.selStuAnswer(name, teaName);

        response.setContentType("application/binary;charset=UTF-8");
        try {
            ServletOutputStream out = response.getOutputStream();
            try {
                //设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name + "考试学生提交答案" + ".xls", "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            String[] titles = {"序号", "学号", "姓名", "班级", "考试科目", "文件名", "上传时间"};
            ExcleUtils.export(titles, "提交记录", out, name, lists);
            return "redirect:/teacher/teacher_after_detail.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/errors/error.jsp";
        }
    }

    @RequestMapping(value = "getAllExams", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Msg getAllExam(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, HttpSession session, HttpServletRequest request) {

        // 查询之前调用startPage，传入分码，以及分页大小
        int spiltPageCount = PagingSize.splitPageSize(request);
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<Exam> lists = examServiceImpl.selAllExam();

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Exam> page = new PageInfo<Exam>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", page);
        System.out.println("总页码：" + page.getPages());
        System.out.println("总记录数：" + page.getTotal());
        return Msg.success().add("pageInfo", page);
    }

    @RequestMapping(value = "getAllExamsOfTea", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Msg getAllExamOfTea(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, String teaId, HttpSession session, HttpServletRequest request) {
        int spiltPageCount = PagingSize.splitPageSize(request);
        // 查询之前调用startPage，传入分码，以及分页大小
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<Exam> lists = examServiceImpl.getAllTeaExam(teaId);

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Exam> page = new PageInfo<Exam>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", page);
        System.out.println("总页码：" + page.getPages());
        System.out.println("总记录数：" + page.getTotal());
        return Msg.success().add("pageInfo", page);
    }

    @RequestMapping(value = "getAllTeaExams", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<Exam> getAllTeaExams(String teaId) {
        return examServiceImpl.getAllTeaExam(teaId);
    }

    @RequestMapping(value = "getAllExamFromStu", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Msg getAllExamFromStu(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, String stuId, HttpSession session, HttpServletRequest request) {
        System.out.println(stuId + "+++++++++++++++++++");
        int spiltPageCount = PagingSize.splitPageSize(request);
        // 查询之前调用startPage，传入分码，以及分页大小
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<the_exam> lists = examServiceImpl.getAllExamFromStu(stuId);

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<the_exam> page = new PageInfo<the_exam>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", page);
        System.out.println("总页码：" + page.getPages());
        System.out.println("总记录数：" + page.getTotal());
        return Msg.success().add("pageInfo", page);
    }

    @RequestMapping(value = "addExam", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void addExam(Exam exam, HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        exam.setE_teacher(teacher.getT_username());  // 考试发布者
        int index = examServiceImpl.insExam(exam);
        if (index >= 1) {
            session.setAttribute("teacher", session.getAttribute("teacher"));
            System.out.println("添加考试成功");
        } else {
            System.out.println("添加考试失败");
        }
    }

    @RequestMapping("goEditExam")
    public String goEditExam(Exam exam, HttpSession session) {
        session.setAttribute("exam", exam);
        session.setAttribute("teacher", session.getAttribute("teacher"));
        return "redirect:/teacher/teacher_addexam.jsp";
    }

    @RequestMapping("editExam")
    public String editExam(String e_oldname, Exam exam, HttpSession session) {
        System.out.println(exam);
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        Exam oldExam = (Exam) session.getAttribute("exam");
        exam.setE_teacher(teacher.getT_name());
        int index = examServiceImpl.updExam(e_oldname, exam);
        if (index >= 1) {
            System.out.println("修改考试成功");
        } else {
            System.out.println("修改考试失败");
        }
        oldExam.setE_name(exam.getE_name());
        oldExam.setE_starttime(exam.getE_starttime());
        oldExam.setE_autostart(exam.getE_autostart());
        oldExam.setE_teacher(teacher.getT_name());
        session.setAttribute("exam", oldExam);
        return "redirect:/teacher/teacher_addexam.jsp";
    }
}